package com.wiz.task;

import java.util.ArrayList;
import java.util.List;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.SchedulerContext;
import org.quartz.SchedulerException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.quartz.QuartzJobBean;

import com.wiz.vo.PayTaskVO;
import com.wiz.vo.to.tencent.WxPayResData;
import com.wiz.vo.type.PayChannelType;
import com.wiz.web.manager.ServiceManager;
import com.wiz.web.service.PayService;
import com.wiz.web.service.impl.PayServiceImpl;

/**
 * 30分钟任务
 * @author Hakeny
 */
public class ThirtyMinTask extends QuartzJobBean{
	private transient final Logger log = LoggerFactory.getLogger(getClass());
	
	private ServiceManager serviceManager;
	
	@Override
	protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
		PayService payService = null;
		if(serviceManager == null){
			SchedulerContext schCtx;
			try {
				schCtx = context.getScheduler().getContext();
				//获取Spring中的上下文    
				ApplicationContext appCtx = (ApplicationContext)schCtx.get("applicationContext");  
				serviceManager = (ServiceManager) appCtx.getBean("serviceManager");
				payService = serviceManager.getPayService();
			} catch (SchedulerException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		log.info("ThirtyMinTask start");
		long nowTime = System.currentTimeMillis();
		List<Integer> indexList = new ArrayList<Integer>();
		for(int i=0;i<PayServiceImpl.taskList.size();i++){//退款
			PayTaskVO vo = PayServiceImpl.taskList.get(i);
			if(vo.getType() == PayChannelType.WEIXIN.getId()){//微信退款
				if(nowTime-vo.getStartTime()>=vo.getIntervalTime()){
					log.info("tradeId="+vo.getWxCriteria().getOutTradeNo()+" refunding");
//					WxPayResData data = payService.refundWxOrder(vo.getHqId(),vo.getWxCriteria());
//					log.info(data.toString());
//					if(data.getResult_code().equals("SUCCESS")){
//						indexList.add(i);
//					}
				}
			}
		}
		for(Integer index:indexList){
			PayServiceImpl.taskList.remove(index);
		}
	}
}
